/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 二叉树前序遍历，中左右，递归解法
 * 时间复杂度O(n)，每个节点遍历一遍；空间复杂度，平均O(logn)，最坏的情况，二叉树是链，为O(n)
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
    if (root === null) return [];

    let arr = [];

    getTreeNodeVal(root, arr);

    return arr
};

function getTreeNodeVal(root, arr) {
    if (root === null) return
    arr.push(root.val)
    getTreeNodeVal(root.left, arr)
    getTreeNodeVal(root.right, arr)
}


/**
 * 二叉树前序遍历-中左右，迭代法。通过栈存储已迭代节点
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    if (root === null) return []

    let temp = root,
        stack = [],
        res = [];

    while (stack.length > 0 || temp !== null) {
        while (temp) {
            res.push(temp.val)
            stack.push(temp)
            temp = temp.left
        }
        temp = stack.pop().right
    }

    return res
}

/**
 * 中左右迭代遍历-前序遍历。往栈中添加当前节点的右节点和左节点，然后依次出栈
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function (root) {
    if(root === null) return []
    let stack = [root],
    res = [];
    while (stack.length > 0) {
        let curNode = stack.pop()
        curNode.right && stack.push(curNode.right)
        curNode.left && stack.push(curNode.left)
        res.push(curNode.val)
    }
    return res
}

function TreeNode(val, left, right) {
    this.val = (val === undefined ? 0 : val)
    this.left = (left === undefined ? null : left)
    this.right = (right === undefined ? null : right)
}

let a = new TreeNode(1)
a.right = new TreeNode(2)
a.right.left = new TreeNode(3)

console.log(preorderTraversal(a));